package com.chaoyong.higo.cainiaowo;

import java.util.ArrayList;
import java.util.List;

import com.chaoyong.higo.bean.ListEntity;
import com.chaoyong.higo.utils.JSONUtil;
import com.chaoyong.higo.utils.PreferencesUtils;
import com.chaoyong.higo.utils.TransferTool;
import com.google.gson.reflect.TypeToken;

import android.content.Context;
import android.util.SparseArray;

public class CartProvider {

	public static final String CART_JSON = "cart_json";

	private SparseArray<ShoppingCart> datas = null;

	private Context mContext;

	public CartProvider(Context context) {
		mContext = context;
		datas = new SparseArray<>();
		listToSpare();
	}

	public void put(ShoppingCart cart) {

		ShoppingCart temp = datas.get(TransferTool.toInt(cart.getId()));

		if (temp != null) {
			temp.setCount(temp.getCount() + 1);
		} else {
			temp = cart;
			temp.setCount(1);
		}

		datas.put(TransferTool.toInt(cart.getId()), temp);

		commit();

	}

	public void put(ListEntity entity) {

		ShoppingCart cart = convertData(entity);
		put(cart);
	}

	public void update(ShoppingCart cart) {
		datas.put(TransferTool.toInt(cart.getId()), cart);
		commit();
	}

	public void delete(ShoppingCart cart) {
		datas.delete(TransferTool.toInt(cart.getId()));
		commit();
	}

	public List<ShoppingCart> getAll() {

		return getDataFromLocal();
	}

	public void commit() {

		List<ShoppingCart> carts = sparseToList();

		PreferencesUtils.putString(mContext, CART_JSON, JSONUtil.toJSON(carts));

	}

	private List<ShoppingCart> sparseToList() {

		int size = datas.size();

		List<ShoppingCart> list = new ArrayList<>(size);
		for (int i = 0; i < size; i++) {

			list.add(datas.valueAt(i));
		}
		return list;

	}

	private void listToSpare() {
		List<ShoppingCart> carts = getDataFromLocal();
		if (carts != null && carts.size() > 0) {
			for (ShoppingCart cart : carts) {
				datas.put(TransferTool.toInt(cart.getId()), cart);
			}
		}
	}

	private List<ShoppingCart> getDataFromLocal() {
		String json = PreferencesUtils.getString(mContext, CART_JSON);
		List<ShoppingCart> carts = null;
		if (json != null) {
			carts = JSONUtil.fromJson(json,
					new TypeToken<List<ShoppingCart>>() {
					}.getType());
		}
		return carts;
	}

	public ShoppingCart convertData(ListEntity item) {
		ShoppingCart cart = new ShoppingCart();

		cart.setId(item.getId());
		cart.setGoods_name(item.getGoods_name());
		cart.setGoods_id(item.getGoods_id());
		cart.setFace_img(item.getFace_img());
		cart.setCover_img(item.getCover_img());
		cart.setExpect(item.getExpect());
		int count = item.getSurplus();
		cart.setSurplus(count);
		cart.setGoods_price(item.getGoods_price());
		
		return cart;
	}
}
